package com.quanyan.place.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.place.biz.ISearchService;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apireq.ReqContractPay;
import com.quanyan.place.entity.apireq.ReqPlaceContractInfoVo;
import com.quanyan.place.entity.apiresp.RespPlaceContractInfoVo;
import com.quanyan.place.mapper.*;
import com.quanyan.place.service.ContractService;
import com.quanyan.place.service.PlaceBaseService;
import com.quanyan.place.service.PlaceBuyService;
import com.quanyan.place.service.PlaceInnerService;
import com.quanyan.place.wrapper.PlaceWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.stereotype.Service;
import org.thymeleaf.fragment.IFragmentSpec;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.quanyan.place.constants.PlaceConstants.BUY_TYPE_FALSE_TIME;
import static com.quanyan.place.constants.PlaceConstants.BUY_TYPE_TIME;
import static com.quanyan.place.constants.PlaceConstants.BUY_TYPE_TRUE_TIME;

/**
 * 场馆内部Serivice实现类
 *
 * Created by liuyaoxin on 2016/8/19.
 */
@Service("contractService")
public class ContractServiceImpl implements ContractService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private TbBizPlaceBuyContractMapper placeBuyContractMapper;

    @Autowired
    private TbBizPlaceBuyContractDetailMapper placeBuyContractDetailMapper;

    @Autowired
    TbBizPlaceMapper placeMapper;

    @Autowired
    TbBizPlaceUnitMapper placeUnitMapper;

    @Autowired
    PlaceBaseService placeBaseService;

    @Autowired
    PlaceMapper pMapper;

    @Autowired
    TbBizPlaceBuyContractHistoryMapper chMapper;

    @Autowired
    TbBizPlaceBuyContractDetailHistoryMapper cdhMapper;

    @Autowired
    TbBizPlaceBuyContractPayMapper contractPayMapper;


    @Autowired
    PlaceInnerService placeInnerService;


    @Autowired
    ISearchService searchService;

    @Autowired
    TbBizPlaceUnitSalePlanMainMapper tbBizPlaceUnitSalePlanMainMapper;
    /**
     * 根据合同ID拿到场馆ID和场地Id
     *
     * @param contractId
     * @return
     */
    @Override
    public List<TbBizPlaceBuyContractDetail> getPlaceIdAndUnitIdByContractId(Integer contractId) {
        /*
        TbBizPlaceBuyContractDetailExample example=new TbBizPlaceBuyContractDetailExample();
        TbBizPlaceBuyContractDetailExample.Criteria criteria=example.createCriteria();
        criteria.andAttractIdEqualTo(contractId);
        List<TbBizPlaceBuyContractDetail> list=placeBuyContractDetailMapper.selectByExample(example);
        */
        ReqPlaceContractInfoVo reqVo = new ReqPlaceContractInfoVo();
        reqVo.setContractId(contractId.toString());
        List<TbBizPlaceBuyContractDetail> list = pMapper.getPlaceIdAndUnitIdByContractId(reqVo);
        return list;

    }

    /**
     * 根据合同ID拿到合同详情信息
     *
     * @param contractId
     * @return
     */

    @Override
    public List<TbBizPlaceBuyContractDetail> getContractDetailByContractId(Integer contractId) {
        TbBizPlaceBuyContractDetailExample example = new TbBizPlaceBuyContractDetailExample();
        TbBizPlaceBuyContractDetailExample.Criteria criteria = example.createCriteria();
        criteria.andAttractIdEqualTo(contractId);
        List<TbBizPlaceBuyContractDetail> list = placeBuyContractDetailMapper.selectByExample(example);
        return list;
    }

    /**
     * 获得合同列表
     *
     * @param reqvo
     * @return
     */
    @Override
    public PageObj<List<RespPlaceContractInfoVo>> getContractList(ReqPlaceContractInfoVo reqvo) {
        if (StringUtils.isEmpty(reqvo.getPlaceName())){
            reqvo.setPlaceName(null);
        }else{
            reqvo.setPlaceName("%"+reqvo.getPlaceName().trim()+"%");
        }
        if (StringUtils.isEmpty(reqvo.getPlaceUnitName())){
            reqvo.setPlaceUnitName(null);
        }else{
            reqvo.setPlaceUnitName("%"+reqvo.getPlaceUnitName().trim()+"%");
        }
        if (StringUtils.isEmpty(reqvo.getSignPeople())){
            reqvo.setSignPeople(null);
        }else{
            reqvo.setSignPeople("%"+reqvo.getSignPeople().trim()+"%");
        }
        if (StringUtils.isEmpty(reqvo.getContractNo())){
            reqvo.setContractNo(null);
        }else{
            reqvo.setContractNo(reqvo.getContractNo().trim());
        }
        if (StringUtils.isEmpty(reqvo.getCode())){
            reqvo.setCode(null);
        }else{
            reqvo.setCode(reqvo.getCode().trim());
        }
        Integer pageNum = reqvo.getPageNum();
        Integer pageSize = reqvo.getPageSize();
        int total = pMapper.getPlaceContractListCount(reqvo);
        reqvo.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<RespPlaceContractInfoVo> respVoList = pMapper.getPlaceContractList(reqvo);
        List<RespPlaceContractInfoVo> contractList=new ArrayList<RespPlaceContractInfoVo>();
        for (RespPlaceContractInfoVo cvo:respVoList){
            RespPlaceContractInfoVo pvo=new RespPlaceContractInfoVo();
            /*
                TbBizPlace tbBizPlace = placeMapper.selectByPrimaryKey(cvo.getPlaceId());
                TbBizPlaceUnit tbBizPlaceUnit= placeUnitMapper.selectByPrimaryKey(cvo.getPlaceUnitId());
                if (tbBizPlace!=null){
                    pvo.setPlaceName(tbBizPlace.getName());
                }
                if (tbBizPlaceUnit!=null){
                    pvo.setPlaceUnitName(tbBizPlaceUnit.getName());
                }
                */
            if(BUY_TYPE_TIME.equals(cvo.getBuyType())){
                pvo.setTypeName("时段买入");
            }else if(PlaceConstants.BUY_TYPE_WHOLE.equals(cvo.getBuyType())){
                pvo.setTypeName("整馆买入");
            }else if(PlaceConstants.BUY_TYPE_GROUP.equals(cvo.getBuyType())){
                pvo.setTypeName("包片买入");
            } else if (PlaceConstants.BUY_TYPE_TRUE_TIME.equals(cvo.getBuyType())) {
                pvo.setTypeName("真包时");
            } else if (PlaceConstants.BUY_TYPE_FALSE_TIME.equals(cvo.getBuyType())) {
                pvo.setTypeName("假包时");
            }
            pvo.setBuyType(cvo.getBuyType());

            if(PlaceConstants.PLACE_CONTRACT_UNEXECUTED.equals(cvo.getStatus())){
                pvo.setStatusName("未执行");
            }else if(PlaceConstants.PLACE_CONTRACT_EXECUTED.equals(cvo.getStatus())){
                pvo.setStatusName("已执行");
            }else if(PlaceConstants.PLACE_CONTRACT_STOP.equals(cvo.getStatus())){
                pvo.setStatusName("已中止");
            }else if(PlaceConstants.PLACE_CONTRACT_END.equals(cvo.getStatus())){
                pvo.setStatusName("已结束");
            }else if(PlaceConstants.PLACE_CONTRACT_DELETE.equals(cvo.getStatus())){
                pvo.setStatusName("已废弃");
            }
            pvo.setId(cvo.getId());
            pvo.setPlaceName(cvo.getPlaceName());
            pvo.setCode(cvo.getCode());
            pvo.setPlaceId(cvo.getPlaceId());
            pvo.setTotalPrice(cvo.getTotalPrice());
            pvo.setSignPeople(cvo.getSignPeople());
            pvo.setBuyDate(cvo.getBuyDate());
            pvo.setContractNo(cvo.getContractNo());
            pvo.setSignDate(cvo.getSignDate());
            pvo.setStatus(cvo.getStatus());
            pvo.setRemark(cvo.getRemark());
            pvo.setCreateTime(cvo.getCreateTime());
            pvo.setUpdateTime(cvo.getUpdateTime());
            pvo.setExpires(cvo.getExpires());
            pvo.setIsVerify(cvo.getIsVerify());

            // 还需要的字段
            pvo.setBillingCycle(cvo.getBillingCycle());
            pvo.setReceiveCompanyName(cvo.getReceiveCompanyName());
            pvo.setTaxRate(cvo.getTaxRate());
            pvo.setInvoice(cvo.getInvoice());
            pvo.setAccountWay(cvo.getAccountWay());
            pvo.setCalRentStartTime(cvo.getCalRentStartTime());
            pvo.setCalRentEndTime(cvo.getCalRentEndTime());

            // 合同明细

            contractList.add(pvo);
        }
        PageObj<List<RespPlaceContractInfoVo>> result = PageObj.create(total, pageNum, pageSize, contractList);
        return result;
    }


    /**
     * 获取合同相关信息
     * @param contractId
     * @return
     */
    @Override
    public TbBizPlaceBuyContract getContractInfoById(Integer contractId) {
        TbBizPlaceBuyContractExample example =new TbBizPlaceBuyContractExample();
        TbBizPlaceBuyContractExample.Criteria criteria=example.createCriteria();
        criteria.andIdEqualTo(contractId);
        example.setDistinct(true);
        List<TbBizPlaceBuyContract> list=placeBuyContractMapper.selectByExample(example);
        if (list!=null&&list.size()>0){
            return list.get(0);
        }else {
            return null;
        }
    }

    /**
     * 更新合同信息
     * @param reqVo
     * @return
     */
    @Override
    public APIResponse updatePlaceContratctInfo(ReqPlaceContractInfoVo reqVo) {
        TbBizPlaceBuyContractExample rExample=new TbBizPlaceBuyContractExample();
        TbBizPlaceBuyContractExample.Criteria rCriteria=rExample.createCriteria();
        TbBizPlaceBuyContract vo=new TbBizPlaceBuyContract();

        if (reqVo!=null) {
            TbBizPlaceBuyContract valCon=this.getContractInfoById(reqVo.getId());
            if (valCon == null) {
                return APIResponse.returnFail("数据库中没有该合同的记录");
            }
            if (!StringUtils.isEmpty(reqVo.getContractNo())) {
                if (valCon.getContractNo()!=null) {
                    if (!valCon.getContractNo().equals(reqVo.getContractNo())) {
                        TbBizPlaceBuyContract voVal = this.getContractInfoByContractNo(reqVo.getContractNo());
                        if (voVal != null) {
                            return APIResponse.returnFail("该合同编号已经在使用！");
                        }
                    }
                }
            }

            //根据合同生效时间，合同失效时间，判断合同的状态
            if(DateUtils.dateTimeCompare(reqVo.getBuyDate(), new Date(), false)){
                vo.setStatus(PlaceConstants.PLACE_CONTRACT_UNEXECUTED);
            }else{
                vo.setStatus(PlaceConstants.PLACE_CONTRACT_EXECUTED);
                if (DateUtils.dateTimeCompare(new Date(),reqVo.getFinishDate(),false)){
                    vo.setStatus(PlaceConstants.PLACE_CONTRACT_END);
                }
            }
            rCriteria.andIdEqualTo(reqVo.getId());
            vo.setTotalPrice(reqVo.getTotalPrice());
            vo.setBillingCycle(reqVo.getBillingCycle());
            vo.setSignPeople(reqVo.getSignPeople());
            vo.setSignDate(reqVo.getSignDate());
            vo.setRemark(reqVo.getRemark());
            vo.setBuyDate(reqVo.getBuyDate());
            //vo.setStatus(reqVo.getStatus());
            vo.setContractNo(reqVo.getContractNo());
            vo.setPhone(reqVo.getPhone());

            vo.setReceiveCompanyName(reqVo.getReceiveCompanyName());
            vo.setTaxRate(reqVo.getTaxRate());
            vo.setInvoice(reqVo.getInvoice());
            vo.setAccountWay(reqVo.getAccountWay());
            vo.setCalRentStartTime(reqVo.getCalRentStartTime());
            vo.setCalRentEndTime(reqVo.getCalRentEndTime());

            // 真假包时可以互改
            Integer destBuyType = reqVo.getBuyType();
            if (destBuyType != null) {
                Integer curBuyType = valCon.getBuyType();
                if ((BUY_TYPE_TIME.equals(curBuyType) || BUY_TYPE_TRUE_TIME.equals(curBuyType) || BUY_TYPE_FALSE_TIME.equals(curBuyType))
                        && (BUY_TYPE_TRUE_TIME.equals(destBuyType) || BUY_TYPE_FALSE_TIME.equals(destBuyType))) {
                    vo.setBuyType(destBuyType);
                } else {
                    return APIResponse.returnFail("只有真假包时可以互改");
                }
            }

            int total = placeBuyContractMapper.updateByExampleSelective(vo, rExample);
            return APIResponse.returnSuccess();
        }else{
            return APIResponse.returnFail("参数不能为空");
        }
    }

    /**
     * 更新合同详情信息
     * @param reqVo
     * @return
     */
    @Override
    public APIResponse updatePlaceContratctDetailInfo(ReqPlaceContractInfoVo reqVo) {
        if (reqVo == null) {
            return APIResponse.returnFail("参数不能为空");
        }

        List<PlaceBuyContractDetail> placeBuyContractDetailList = reqVo.getPlaceBuyContractDetails();
        if (placeBuyContractDetailList == null||placeBuyContractDetailList.size()==0) {
            TbBizPlaceBuyContractDetailExample rExample = new TbBizPlaceBuyContractDetailExample();
            TbBizPlaceBuyContractDetailExample.Criteria rCriteria = rExample.createCriteria();
            TbBizPlaceBuyContractDetail voDetail = new TbBizPlaceBuyContractDetail();

            rCriteria.andAttractIdEqualTo(reqVo.getId());
            voDetail.setBuyDate(reqVo.getBuyDate());
            //voDetail.setFinishDate(DateUtils.addTime(reqVo.getBuyDate(),(int)(reqVo.getExpires()*12),0));
            voDetail.setFinishDate(reqVo.getFinishDate());
            //voDetail.setExpires(reqVo.getExpires());
            placeBuyContractDetailMapper.updateByExampleSelective(voDetail, rExample);
            return APIResponse.returnSuccess();
        }

        for (PlaceBuyContractDetail placeBuyContractDetail : placeBuyContractDetailList) {
            TbBizPlaceBuyContractDetail voDetail = new TbBizPlaceBuyContractDetail();
            voDetail.setBuyDate(reqVo.getBuyDate());
            //voDetail.setFinishDate(DateUtils.addTime(reqVo.getBuyDate(),(int)(reqVo.getExpires()*12),0));
            voDetail.setFinishDate(reqVo.getFinishDate());
            //voDetail.setExpires(reqVo.getExpires());

            voDetail.setTimePrice(placeBuyContractDetail.getTimePrice());

            TbBizPlaceBuyContractDetailExample rExample = new TbBizPlaceBuyContractDetailExample();
            TbBizPlaceBuyContractDetailExample.Criteria rCriteria = rExample.createCriteria();
            rCriteria.andAttractIdEqualTo(reqVo.getId());
            rCriteria.andIdEqualTo(placeBuyContractDetail.getId());
            placeBuyContractDetailMapper.updateByExampleSelective(voDetail, rExample);
        }

        return APIResponse.returnSuccess();
    }

    /**
     * 废弃合同
     * @param reqVo
     * @return
     */
    @Override
    public APIResponse deletePlaceContratctInfo(ReqPlaceContractInfoVo reqVo) {
        TbBizPlaceBuyContractExample rExample=new TbBizPlaceBuyContractExample();
        TbBizPlaceBuyContractExample.Criteria rCriteria=rExample.createCriteria();
        rCriteria.andIdEqualTo(reqVo.getId());
        TbBizPlaceBuyContract vo=new  TbBizPlaceBuyContract();
        vo.setDeleteReason(reqVo.getDeleteReason());
        vo.setStatus(PlaceConstants.PLACE_CONTRACT_DELETE);
        vo.setIsDelete((byte)1);
        placeBuyContractMapper.updateByExampleSelective(vo,rExample);
        return APIResponse.returnSuccess();
    }

    /**
     * 废弃合同详情
     * @param reqVo
     * @return
     */
    @Override
    public APIResponse deletePlaceContratctDetailInfo(ReqPlaceContractInfoVo reqVo) {
        TbBizPlaceBuyContractDetailExample rExample=new TbBizPlaceBuyContractDetailExample();
        TbBizPlaceBuyContractDetailExample.Criteria rCriteria=rExample.createCriteria();
        rCriteria.andAttractIdEqualTo(reqVo.getId());
        TbBizPlaceBuyContractDetail vo=new TbBizPlaceBuyContractDetail();
        vo.setIsDelete((byte)1);
        placeBuyContractDetailMapper.updateByExampleSelective(vo,rExample);
        return APIResponse.returnSuccess();
    }



    /**
     * 中止合同
     * @param reqVo
     * @return
     */
    @Override
    public APIResponse stopPlaceContratct(ReqPlaceContractInfoVo reqVo) {
        TbBizPlaceBuyContractExample rExample=new TbBizPlaceBuyContractExample();
        TbBizPlaceBuyContractExample.Criteria rCriteria=rExample.createCriteria();
        if (reqVo!=null){
            rCriteria.andIdEqualTo(reqVo.getId());
            TbBizPlaceBuyContract vo=new TbBizPlaceBuyContract();
            vo.setStatus(PlaceConstants.PLACE_CONTRACT_STOP);
            vo.setStopReason(reqVo.getStopReason());
            placeBuyContractMapper.updateByExampleSelective(vo,rExample);
            return APIResponse.returnSuccess();
        }else{
            return APIResponse.returnFail("参数不能为空");
        }
    }

    //设置合同审批状态0: 审核中　１:完成审核
    @Override
    public APIResponse setVerifyFlag(Integer contractId, Integer newStatus) {
        TbBizPlaceBuyContractExample rExample=new TbBizPlaceBuyContractExample();
        TbBizPlaceBuyContractExample.Criteria rCriteria=rExample.createCriteria();
        if (contractId != null){
            rCriteria.andIdEqualTo(contractId);
            TbBizPlaceBuyContract vo = new TbBizPlaceBuyContract();
            vo.setIsVerify(newStatus);
            placeBuyContractMapper.updateByExampleSelective(vo,rExample);
            return APIResponse.returnSuccess();
        }else{
            return APIResponse.returnFail("参数不能为空");
        }
    }

    // 检查合同字段是否符合审核条件
    @Override
    public APIResponse CheckContractForVerify(Integer contractId) {
        // 数据库中读取合同信息
        TbBizPlaceBuyContract contract = this.getContractInfoById(contractId);
        if (null == contract) {
            return APIResponse.returnFail("无法获取合同信息");
        }

        // 判断算租日期是否设置
        if (contract.getCalRentStartTime() == null
                || contract.getCalRentEndTime() == null) {
            return APIResponse.returnFail("没有计租日期无法计算成本");
        }

        //  todo... 其他检查
        return APIResponse.returnSuccess();
    }

    //审批合同
    @Override
    public APIResponse verifyContratctInfo(ReqPlaceContractInfoVo reqVo) {
        TbBizPlaceBuyContractExample rExample=new TbBizPlaceBuyContractExample();
        TbBizPlaceBuyContractExample.Criteria rCriteria=rExample.createCriteria();
        if (reqVo!=null){
            rCriteria.andIdEqualTo(reqVo.getId());
            TbBizPlaceBuyContract vo=new TbBizPlaceBuyContract();
            vo.setIsVerify(PlaceConstants.PLACE_CONTRACT_VERIFY_YES);
            placeBuyContractMapper.updateByExampleSelective(vo,rExample);
            return APIResponse.returnSuccess();
        }else{
            return APIResponse.returnFail("参数不能为空");
        }
    }

    /**
     * 中止合同详情
     * @param reqVo
     * @return
     */
    @Override
    public APIResponse stopPlaceContratctDetail(ReqPlaceContractInfoVo reqVo) {
        TbBizPlaceBuyContractDetailExample rExample=new TbBizPlaceBuyContractDetailExample();
        TbBizPlaceBuyContractDetailExample.Criteria rCriteria=rExample.createCriteria();
        if (reqVo!=null){
            rCriteria.andIdEqualTo(reqVo.getId());
            TbBizPlaceBuyContractDetail vo=new TbBizPlaceBuyContractDetail();
            //vo.setStatus(3);
            vo.setIsDelete((byte) 1);
            placeBuyContractDetailMapper.updateByExampleSelective(vo,rExample);
            return APIResponse.returnSuccess();
        }else{
            return APIResponse.returnFail("参数不能为空");
        }
    }

    /**
     * 合同导出
     * @param reqVo
     * @return
     */
    @Override
    public List<RespPlaceContractInfoVo> expotrContractList(ReqPlaceContractInfoVo reqVo) {

        if (StringUtils.isEmpty(reqVo.getPlaceName())){
            reqVo.setPlaceName(null);
        }else{
            reqVo.setPlaceName("%"+reqVo.getPlaceName().trim()+"%");
        }
        if (StringUtils.isEmpty(reqVo.getPlaceUnitName())){
            reqVo.setPlaceUnitName(null);
        }else{
            reqVo.setPlaceUnitName("%"+reqVo.getPlaceUnitName().trim()+"%");
        }
        if (StringUtils.isEmpty(reqVo.getSignPeople())){
            reqVo.setSignPeople(null);
        }else{
            reqVo.setSignPeople("%"+reqVo.getSignPeople()+"%");
        }
        if (StringUtils.isEmpty(reqVo.getCode())){
            reqVo.setCode(null);
        }else{
            reqVo.setCode("%"+reqVo.getCode().trim()+"%");
        }
        if (StringUtils.isEmpty(reqVo.getContractNo())){
            reqVo.setContractNo(null);
        }else{
            reqVo.setContractNo("%"+reqVo.getContractNo().trim()+"%");
        }
        SimpleDateFormat smf= new SimpleDateFormat("yyyy-MM-dd");
        List<RespPlaceContractInfoVo> respVoList = pMapper.getPlaceContractList(reqVo);
        List<RespPlaceContractInfoVo> contractList=new ArrayList<RespPlaceContractInfoVo>();
        for (RespPlaceContractInfoVo cvo:respVoList){
            RespPlaceContractInfoVo pvo=new RespPlaceContractInfoVo();
            if(BUY_TYPE_TIME.equals(cvo.getBuyType())){
                pvo.setTypeName("时段买入");
            } else if(PlaceConstants.BUY_TYPE_WHOLE.equals(cvo.getBuyType())){
                pvo.setTypeName("整馆买入");
            } else if(PlaceConstants.BUY_TYPE_GROUP.equals(cvo.getBuyType())){
                pvo.setTypeName("包片买入");
            } else if(PlaceConstants.BUY_TYPE_TRUE_TIME.equals(cvo.getBuyType())){
                pvo.setTypeName("真包时");
            } else if(PlaceConstants.BUY_TYPE_FALSE_TIME.equals(cvo.getBuyType())){
                pvo.setTypeName("假包时");
            }
            if(PlaceConstants.PLACE_CONTRACT_UNEXECUTED.equals(cvo.getStatus())){
                pvo.setStatusName("未执行");
            }else if(PlaceConstants.PLACE_CONTRACT_EXECUTED.equals(cvo.getStatus())){
                pvo.setStatusName("已执行");
            }else if(PlaceConstants.PLACE_CONTRACT_STOP.equals(cvo.getStatus())){
                pvo.setStatusName("已中止");
            }else if(PlaceConstants.PLACE_CONTRACT_END.equals(cvo.getStatus())){
                pvo.setStatusName("已结束");
            }
            pvo.setContractNo(cvo.getContractNo());
            pvo.setPlaceName(cvo.getPlaceName());
            pvo.setPlaceUnitName(cvo.getPlaceUnitName());
            pvo.setPlaceId(cvo.getPlaceId());
            pvo.setTotalPrice(cvo.getTotalPrice());
            pvo.setSignPeople(cvo.getSignPeople());
            pvo.setBuyDate(cvo.getBuyDate());
            pvo.setContractNo(cvo.getContractNo());
            pvo.setsDate(smf.format(cvo.getSignDate()));
            pvo.setRemark(cvo.getRemark());
            pvo.setcTime(smf.format(cvo.getCreateTime()));
            pvo.setuTime(smf.format(cvo.getUpdateTime()));
            pvo.setExpires(cvo.getExpires());
            contractList.add(pvo);
        }
        return contractList;
    }

    /**
     * 任务调度：检查未执行和已执行的合同并修改合同状态：未执行改成已执行，已执行改成已过期
     */
    @Override
    public void updateContractStatus(){
        //取出合同状态是未执行或已执行的合同，
        List<TbBizPlaceBuyContractDetail> list=pMapper.getContractIdAndFinishDateList();
            for (TbBizPlaceBuyContractDetail vo:list){
                if (vo.getFinishDate()!=null) {
                    if (vo.getBuyDate()!=null) {
                        if (DateUtils.dateTimeCompare(new Date(), vo.getBuyDate(), false)) {
                           /* ReqPlaceContractInfoVo reqVo = new ReqPlaceContractInfoVo();
                            reqVo.setId(vo.getAttractId());
                            reqVo.setStatus(PlaceConstants.PLACE_CONTRACT_EXECUTED);*/
                            try {
                                TbBizPlaceBuyContractExample rExample=new TbBizPlaceBuyContractExample();
                                TbBizPlaceBuyContractExample.Criteria rCriteria=rExample.createCriteria();
                                TbBizPlaceBuyContract contract=new TbBizPlaceBuyContract();
                                rCriteria.andIdEqualTo(vo.getAttractId());
                                contract.setStatus(PlaceConstants.PLACE_CONTRACT_EXECUTED);
                                 placeBuyContractMapper.updateByExampleSelective(contract, rExample);
                                //this.updatePlaceContratctInfo(reqVo);
                            }catch(Exception e){
                                logger.info("更新失败---->"+e.getMessage());
                            }

                        }
                    }
                    if (DateUtils.dateTimeCompare(new Date(),vo.getFinishDate(), false)) {
                        try{
                            TbBizPlaceBuyContractExample rExample=new TbBizPlaceBuyContractExample();
                            TbBizPlaceBuyContractExample.Criteria rCriteria=rExample.createCriteria();
                            TbBizPlaceBuyContract contract=new TbBizPlaceBuyContract();
                            rCriteria.andIdEqualTo(vo.getAttractId());
                            contract.setStatus(PlaceConstants.PLACE_CONTRACT_END);
                            placeBuyContractMapper.updateByExampleSelective(contract, rExample);
                            //当合同到期时，更新场馆状态，场地状态及solr
                            this.updatePlaceStatusWhenContractStopOrDelete(vo.getPlaceId(),vo.getAttractId());
                        }catch (Exception e){
                            logger.info("更新失败---->"+e.getMessage());
                        }
                        vo.getPlaceId();
                      /*  ReqPlaceContractInfoVo reqVo = new ReqPlaceContractInfoVo();
                        reqVo.setId(vo.getAttractId());
                        reqVo.setStatus(PlaceConstants.PLACE_CONTRACT_END);
                        this.updatePlaceContratctInfo(reqVo);*/
                    }
                }
            }
    }


    /**
     * 根据编号查找合同信息
     * @param contractNo
     * @return
     */

    @Override
    public TbBizPlaceBuyContract getContractInfoByContractNo(String contractNo) {
        TbBizPlaceBuyContractExample example =new TbBizPlaceBuyContractExample();
        TbBizPlaceBuyContractExample.Criteria criteria=example.createCriteria();
        criteria.andContractNoEqualTo(contractNo);
        List<TbBizPlaceBuyContract> list=placeBuyContractMapper.selectByExample(example);
        if (list!=null&&list.size()>0){
            return list.get(0);
        }else {
            return null;
        }
    }

    /**
     * 根据场馆ID获取合同列表
     * @param reqVo
     * @return
     */
    @Override
    public List<RespPlaceContractInfoVo> getContractListByPlaceId(ReqPlaceContractInfoVo reqVo) {
        List<RespPlaceContractInfoVo> list=pMapper.getContractListByPlaceId(reqVo);
        return list;
    }

    /**
     * 备份合同
     *
     * @param
     * @param contractId, 当前合同版本
     * @return
     */
    @Override
    public APIResponse BackupContractHistory(Integer contractId, Integer version) {
        // 先读取合同信息
        TbBizPlaceBuyContract contract = this.getContractInfoById(contractId);
        if (null == contract) {
            return APIResponse.returnFail("无法获取合同信息");
        }

        // 插入到history表中
        TbBizPlaceBuyContractHistory tbBizPlaceBuyContractHistory = new TbBizPlaceBuyContractHistory();
        tbBizPlaceBuyContractHistory.setCid(contract.getId());
        tbBizPlaceBuyContractHistory.setContractVersion(version);

        tbBizPlaceBuyContractHistory.setContractNo(contract.getContractNo());
        tbBizPlaceBuyContractHistory.setBuyType(contract.getBuyType());
        tbBizPlaceBuyContractHistory.setBuyDate(contract.getBuyDate());
        tbBizPlaceBuyContractHistory.setTotalPrice(contract.getTotalPrice());
        tbBizPlaceBuyContractHistory.setBillingCycle(contract.getBillingCycle());
        tbBizPlaceBuyContractHistory.setPlaceId(contract.getPlaceId());
        tbBizPlaceBuyContractHistory.setCreateTime(contract.getCreateTime());
        tbBizPlaceBuyContractHistory.setUpdateTime(contract.getUpdateTime());
        tbBizPlaceBuyContractHistory.setDeptId(contract.getDeptId());
        tbBizPlaceBuyContractHistory.setUid(contract.getUid());
        tbBizPlaceBuyContractHistory.setIsDelete(contract.getIsDelete());
        tbBizPlaceBuyContractHistory.setSignDate(contract.getSignDate());
        tbBizPlaceBuyContractHistory.setSignPeople(contract.getSignPeople());
        tbBizPlaceBuyContractHistory.setPhone(contract.getPhone());
        tbBizPlaceBuyContractHistory.setReceiveCompanyName(contract.getRemark());
        tbBizPlaceBuyContractHistory.setStatus(contract.getStatus());
        tbBizPlaceBuyContractHistory.setStopReason(contract.getStopReason());
        tbBizPlaceBuyContractHistory.setDeleteReason(contract.getDeleteReason());
        tbBizPlaceBuyContractHistory.setReceiveCompanyName(contract.getReceiveCompanyName());
        tbBizPlaceBuyContractHistory.setTaxRate(contract.getTaxRate());
        tbBizPlaceBuyContractHistory.setInvoice(contract.getInvoice());
        tbBizPlaceBuyContractHistory.setAccountWay(contract.getAccountWay());
        tbBizPlaceBuyContractHistory.setCalRentStartTime(contract.getCalRentStartTime());
        tbBizPlaceBuyContractHistory.setCalRentEndTime(contract.getCalRentEndTime());

        // 第一版合同
        if (version == 1) {
            tbBizPlaceBuyContractHistory.setExecutionStartTime(contract.getCalRentStartTime());
        } else {
            // 新合同明天开始生效
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, 1);
            Date tomorrow = cal.getTime();
            tbBizPlaceBuyContractHistory.setExecutionStartTime(tomorrow);
        }
        tbBizPlaceBuyContractHistory.setExecutionEndTime(contract.getCalRentEndTime());

        int ret = chMapper.insertSelective(tbBizPlaceBuyContractHistory);
        if (ret < 1) {
            return  APIResponse.returnFail("备份合同信息到history表中失败");
        }
        int hid = tbBizPlaceBuyContractHistory.getId();

        // 备份detail数据
        List<TbBizPlaceBuyContractDetail> details = this.getContractDetailByContractId(contractId);
        if (details != null && details.size() > 0) {
            for (TbBizPlaceBuyContractDetail detail : details) {
                TbBizPlaceBuyContractDetailHistory detailHistory = new TbBizPlaceBuyContractDetailHistory();
                detailHistory.setAttractHistoryId(hid);
                detailHistory.setDid(detail.getId());
                detailHistory.setAttractId(detail.getAttractId());
                detailHistory.setPlaceId(detail.getPlaceId());
                detailHistory.setPlaceUnitId(detail.getPlaceUnitId());
                detailHistory.setPlaceUnitPrice(detail.getPlaceUnitPrice());
                detailHistory.setPlaceUnitExpires(detail.getPlaceUnitExpires());
                detailHistory.setBuyType(detail.getBuyType());
                detailHistory.setExpiresUnit(detail.getExpiresUnit());
                detailHistory.setDateRange(detail.getDateRange());
                detailHistory.setBuyStartTime(detail.getBuyStartTime());
                detailHistory.setBuyEndTime(detail.getBuyEndTime());
                detailHistory.setCreateTime(detail.getCreateTime());
                detailHistory.setUpdateTime(detail.getUpdateTime());
                detailHistory.setUid(detail.getUid());
                detailHistory.setDeptId(detail.getDeptId());
                detailHistory.setFinishDate(detail.getFinishDate());
                detailHistory.setIsDelete(detail.getIsDelete());
                detailHistory.setBuyDate(detail.getBuyDate());
                detailHistory.setIsExpire(detail.getIsExpire());
                detailHistory.setTimePrice(detail.getTimePrice());

                cdhMapper.insertSelective(detailHistory);
            }
        }

        return APIResponse.returnSuccess();
    }

    /**
     * 历史更新合同执行区间
     *
     * @param
     * @return
     */
    @Override
    public APIResponse UpdateContractExecuteTime(Integer contractId, Integer version) {
        TbBizPlaceBuyContractHistoryExample rExample = new TbBizPlaceBuyContractHistoryExample();
        TbBizPlaceBuyContractHistoryExample.Criteria rCriteria = rExample.createCriteria();

        rCriteria.andCidEqualTo(contractId);
        rCriteria.andContractVersionEqualTo(version);

        TbBizPlaceBuyContractHistory bch = new TbBizPlaceBuyContractHistory();
        bch.setExecutionEndTime(new Date());  // 今天作为截止时间

        chMapper.updateByExampleSelective(bch, rExample);
        return APIResponse.returnSuccess();
    }


    @Override
    public APIResponse ClearContractHistory(Integer contractId) {
        TbBizPlaceBuyContractHistoryExample rExample = new TbBizPlaceBuyContractHistoryExample();
        TbBizPlaceBuyContractHistoryExample.Criteria rCriteria = rExample.createCriteria();

        rCriteria.andCidEqualTo(contractId);
        chMapper.deleteByExample(rExample);

        return APIResponse.returnSuccess();
    }


    @Override
    public APIResponse<?> getContractPayList(Integer contractId) {
        TbBizPlaceBuyContractPayExample example = new TbBizPlaceBuyContractPayExample();
        TbBizPlaceBuyContractPayExample.Criteria criteria = example.createCriteria();

        criteria.andContractIdEqualTo(contractId);
        List<TbBizPlaceBuyContractPay> list = contractPayMapper.selectByExample(example);

        return APIResponse.returnSuccess(list);
    }

    @Override
    public APIResponse<?> updateContractPay(ReqContractPay reqVo) {
        // 检查合同是否存在
        TbBizPlaceBuyContract contract = getContractInfoById(reqVo.getContractId());
        if (contract == null) {
            return APIResponse.returnFail("要记录支付的合同不存在");
        }

        // 检查金额是否正确
        BigDecimal total = BigDecimal.ZERO;
        total = total.add(reqVo.getSiteFee());
        total = total.add(reqVo.getTaxFee());
        total = total.add(reqVo.getDepositFee());
        if (total.compareTo(reqVo.getTotalFee()) != 0) {
            return APIResponse.returnFail("支付总金额不正确,合计金额=场地费+税金+押金");
        }

        TbBizPlaceBuyContractPay pay = new TbBizPlaceBuyContractPay();
        BeanUtils.copyProperties(reqVo, pay);

        int ret = -1;
        if (reqVo.getId() == null || reqVo.getId().equals(0)) {
            ret = contractPayMapper.insertSelective(pay);
        } else {
            TbBizPlaceBuyContractPayExample example = new TbBizPlaceBuyContractPayExample();
            TbBizPlaceBuyContractPayExample.Criteria criteria = example.createCriteria();

            criteria.andIdEqualTo(reqVo.getId());
            ret = contractPayMapper.updateByExampleSelective(pay, example);
        }

        if (ret < 1) {
            return APIResponse.returnFail("更新数据库失败");
        }

        return APIResponse.returnSuccess();
    }


    @Override
    public APIResponse<?> deleteContractPay(ReqContractPay reqVo) {
        Integer id = reqVo.getId();

        if (id == null || id <= 0) {
            return APIResponse.returnFail("非法的支付批次参数");
        }

        TbBizPlaceBuyContractPayExample example = new TbBizPlaceBuyContractPayExample();
        TbBizPlaceBuyContractPayExample.Criteria criteria = example.createCriteria();

        criteria.andIdEqualTo(id);
        int ret = contractPayMapper.deleteByExample(example);
        if (ret < 1) {
            return APIResponse.returnFail("从数据表中删除合同支付失败");
        }

        return APIResponse.returnSuccess();
    }

    //当合同到期结束时，更新场馆状态，场地状态及solr
    public void updatePlaceStatusWhenContractStopOrDelete(Integer placeId,Integer contractId){
        ReqPlaceContractInfoVo reqVo=new ReqPlaceContractInfoVo();
        reqVo.setPlaceId(placeId);
        List<TbBizPlaceBuyContractDetail> detailVoList=this.getPlaceIdAndUnitIdByContractId(contractId);
        //将场地改成未签约
        for(TbBizPlaceBuyContractDetail detailVo:detailVoList){
            TbBizPlaceUnit placeUnitVo=new TbBizPlaceUnit();
            placeUnitVo.setIsSign(PlaceConstants.IS_SIGN_NO);
            placeUnitVo.setId(detailVo.getPlaceUnitId());
            placeBaseService.updatePlaceUnitBySelective(placeUnitVo);
            // 将所有该场地下的销售计划置为无效
            placeInnerService.updateSalePlanToInvalidate(detailVo.getPlaceUnitId(),Constants.BYTE_TWO);
        }
        if (this.getContractListByPlaceId(reqVo).size()==0){
            //修改场馆签约状态
            TbBizPlace vo=new TbBizPlace();
            vo.setIsSign(PlaceConstants.IS_SIGN_NO);
            vo.setIsShelves(Constants.ZERO); // 下架
            vo.setId(reqVo.getPlaceId());
            placeBaseService.updatePlaceBySelective(vo);
            // 将所有该场馆下的销售计划置为无效
            placeInnerService.updateSalePlanToInvalidate(placeId,Constants.BYTE_ONE);
            this.updateSolrIndex(reqVo.getPlaceId());
        }
        //签约时段  将销售计划模板置为无效
        for(TbBizPlaceBuyContractDetail detailVo : detailVoList){
            TbBizPlaceUnitSalePlanMainExample placeUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
            TbBizPlaceUnitSalePlanMainExample.Criteria criteria = placeUnitSalePlanMainExample.createCriteria();
            criteria.andPlaceIdEqualTo(detailVo.getPlaceId());
            criteria.andPlaceUnitIdEqualTo(detailVo.getPlaceUnitId());
            if (detailVo.getBuyStartTime() != null){
                criteria.andStartTimeEqualTo(detailVo.getBuyStartTime());
            }
            if (detailVo.getBuyEndTime() != null){
                criteria.andEndTimeEqualTo(detailVo.getBuyEndTime());
            }
            TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain = new TbBizPlaceUnitSalePlanMain();
            tbBizPlaceUnitSalePlanMain.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
            tbBizPlaceUnitSalePlanMainMapper.updateByExampleSelective(tbBizPlaceUnitSalePlanMain,placeUnitSalePlanMainExample);
        }

    }

    public boolean updateSolrIndex(Integer placeId){
        try {
            searchService.deleteDocById(placeId, PlaceConstants.SOLR_INDEX_PLAN);
            searchService.deleteDocById(placeId, PlaceConstants.SOLR_INDEX_PLACE);
            TbBizPlace tbBizPlace = new TbBizPlace();
            tbBizPlace.setId(placeId);
            this.searchService.addPlaceIndex(tbBizPlace, null);
            return true;
        }catch (Exception e){
            logger.error("更新索引失败placeid:{}", placeId);
        }
        return false;
    }

}
